#include "firework.h"

GLuint firework::index = -100;

particle::particle(){
	this->startPos = Vector3();
	this->endPos = Vector3();
	this->velocity = Vector3();
	for(int i = 0; i < 3; i++){
		particleColor[i] = RangeRand(0.0f, 1.0f);
	}
}

particle::particle(Vector3 velocity, Vector3 startPos){
	this->velocity = velocity;
	this->startPos = startPos;
	this->endPos = startPos;
	for(int i = 0; i < 3; i++){
		particleColor[i] = RangeRand(0.0f, 1.0f);
	}

}

void particle::updateEnd(double time){
	this->endPos = this->endPos + this->velocity * time;
	this->startPos = this->startPos + this->velocity *(time/2.0f);
}

firework::firework(){
	this->numParticles = 500;
	this->launchPosition = Vector3();
	this->launchVelocity = Vector3(0, 50.0f, 0);
	this->launching = true;
	this->launchHeight = 100;
	this->particleIterations = 100;

}

firework::firework(int numParticles, Vector3 position, Vector3 launchVelocity, float launchHeight){
	this->numParticles = numParticles;
	this->launchPosition = position;
	this->launchVelocity = launchVelocity;
	this->launching = true;
	this->launchHeight = launchHeight;
	this->particleIterations = 100;
}


void firework::updateFirework(double elapsedTime){
	if(launching){
		launchPosition =  launchPosition + (launchVelocity * elapsedTime);
	}
	else{
		for(int i = 0; i < activeParticles.size(); i++){
			activeParticles[i].updateEnd(elapsedTime);
		}
	}
}

bool firework::draw(){
	if(launching){
		float specReflection[] = { 0.3f, 0.3f, 0.3f, 1.0f };
		float baseColor[] = {.3f, .9f, .1f };

		glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE, baseColor);	
		glMateriali(GL_FRONT, GL_SHININESS, 100);
		glMaterialfv(GL_FRONT, GL_SPECULAR, specReflection);
		glCallList(index);
		if(launchPosition.y >= launchHeight){
			launching = false;
			for(int i = 0; i < numParticles; i++){
				Vector3 unitVec = randUnitSphereVector();
				particle tmp = particle(unitVec * 250.0f, this->getPosition() /*+ unitVec * 50*/);
				this->activeParticles.push_back(tmp);
			}
		}
		return true;
	}
	else{
		this->particleIterations--;
		if(particleIterations == 0) return false;
		glDisable(GL_LIGHTING);

		for(int i = 0; i < activeParticles.size(); i++){

			glPushMatrix();

				glColor3fv(activeParticles[i].particleColor);
				glLineWidth(1.0f);

				glBegin( GL_LINES );
					glVertexVector(activeParticles[i].startPos);
					glVertexVector(activeParticles[i].endPos);
				glEnd();
			glPopMatrix();

		}

		glEnable(GL_LIGHTING);

		return true;
	}
	return false;

}

void firework::setupDisplayList(){
	index = glGenLists(1);
	glNewList(index, GL_COMPILE);
	glPushMatrix();
	glScalef(.5f, 1.0f, .5f);
	GLUquadricObj* body = gluNewQuadric();
	gluSphere(body, 10, 20, 20);
	gluDeleteQuadric(body);
	glPopMatrix();
	glEndList();

}

Vector3 firework::getPosition(){
	return launchPosition;
}